grammar SqlMapping;

//options{backtrack=true; memoize=true;}

@lexer::header { 
package org.sqlproc.engine.impl;
}

@header { 
package org.sqlproc.engine.impl;
}

@lexer::members {
  private List<ErrorMsg> errors = new ArrayList<ErrorMsg>();
  public List<ErrorMsg> getErrors() {
    return errors;
  }

  public String getErrorMessage(RecognitionException e, String[] tokenNames) {
    String msg = super.getErrorMessage(e,tokenNames);
    errors.add(ParserUtils.create(msg,e,tokenNames));
    return msg;
  }
}

@members {
  public static void main(String[] args) throws Exception {
    SqlMappingLexer lex = new SqlMappingLexer(new ANTLRFileStream(args[0]));
    CommonTokenStream tokens = new CommonTokenStream(lex);
    SqlMappingParser parser = new SqlMappingParser(tokens);

    try {
      parser.parse();
    } catch (RecognitionException e)  {
      e.printStackTrace();
    }
  }

  private Token getLastToken() {
    return input.LT(-1);
  }


  private List<ErrorMsg> errors = new ArrayList<ErrorMsg>();
  public List<ErrorMsg> getErrors() {
    return errors;
  }

  @Override
  public void reportError(RecognitionException e) {
    String msg = super.getErrorMessage(e,tokenNames);
    errors.add(ParserUtils.create(msg,e,tokenNames));
  }
}

parse returns [SqlMappingRule sqlMapping]
@init{ $sqlMapping = new SqlMappingRule(); }
:
(
  WS*
  sqlMappingItem=mapping {$sqlMapping.addMapping(sqlMappingItem);}
  (WS+ sqlMappingItem=mapping {$sqlMapping.addMapping(sqlMappingItem);})*
  WS* EOF 
)
;

mapping returns[SqlMappingItem sqlMappingItem]
:
  
  (
    IDENT { $sqlMappingItem = new SqlMappingItem(getLastToken().getText()); }
    (STRING
    mappingType[$sqlMappingItem]
    (STRING
    IDENT { $sqlMappingItem.addName(getLastToken().getText()); }
    (
      DOT IDENT { $sqlMappingItem.addName(getLastToken().getText()); }
    )*)?
    )?
  )
;
/*
parse returns [SqlMapping sqlMapping]
: 
  result=mappings {$sqlMapping = result;}
  WS*
  EOF;
*/



mappingType [SqlMappingItem sqlMappingItem]
:
      (IDENT { $sqlMappingItem.setMetaType(getLastToken().getText()); })?
;


IDENT: ('a'..'z' | 'A'..'Z') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_' | '-')* ;
WS:    (' ' | '\t')+ ;
DOT:    '.'  ;
STRING: '$' | '^'  ;
